

import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:logger/logger.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:scan/scan.dart';
import 'package:xim/common/module/qr.dart';
import 'package:xim/common/style/colors.dart';
import 'package:xim/http/apis.dart';
import 'package:xim/router/index.dart';
import 'package:xim/widget/common/state.dart';

var log = Logger();

/// 二维码扫描页面
class QrScanPage extends StatefulWidget {
  const QrScanPage({Key? key}) : super(key: key);

  @override
  State<QrScanPage> createState() => _QrScanPageState();
}

class _QrScanPageState extends State<QrScanPage> with AppBarMixin, BrightnessMode{

  ModelColor bgColor = ModelColor(darkColor: const Color(0xff111111), lightColor: const Color(0xffededed));
  ModelColor textColor = ModelColor(lightColor: const Color((0xff161616)), darkColor: const Color(0xffcecece));

  @override
  List<ModelColor> get brightnessColors => [bgColor,textColor];

  @override
  String get appBarTitle => "扫一扫";

  @override
  double get elevation => 0;

  @override
  Color get appBarBgColor => bgColor.color;

  @override
  TextStyle get appBarTitleStyle => TextStyle(fontSize: 14, color: textColor.color);

  @override
  IconThemeData get iconTheme => IconThemeData(color: textColor.color);

  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  Barcode? result;
  QRViewController? controller;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    initModelColor(context);
    return Scaffold(
      backgroundColor: bgColor.color,
      appBar: appBar,
      body: Column(
        children: <Widget>[
          const Expanded(
            flex: 1,
            child: SizedBox(),
          ),
          Expanded(
            flex: 6,
            child: Stack(
              children: [
                QRView(
                  key: qrKey,
                  overlay: QrScannerOverlayShape(borderColor: Colors.white),
                  cameraFacing: CameraFacing.back,
                  onQRViewCreated: _onQRViewCreated,
                ),
                Positioned(
                  right: 8,
                  bottom: 8,
                  child: Column(
                    children: [
                      scanIcons(Icons.flashlight_on_outlined, (){
                        controller?.toggleFlash();
                      }),
                      const SizedBox(height: 18,),
                      scanIcons(Icons.image_outlined, () async {
                        closeFlash();
                        var image =  await pickerImage();
                        if(image!=null){
                          var res = await Scan.parse(image.path);
                          if(res !=null){
                            qrResultAction(res);
                          }else{
                            // 没有识别到二维码
                            toast("没有识别到二维码");
                          }
                        }
                      }),
                    ],
                  )
                  ,
                )
              ],
            ),
          ),
          Expanded(
            flex: 2,
            child: Center(
              child: Text('扫描中，请耐心等待', style: TextStyle(color: textColor.color, fontSize: 13),),
            ),
          )
        ],
      ),
    );
  }

  Future<XFile?> pickerImage() async {
    final ImagePicker picker = ImagePicker();
    return  await picker.pickImage(requestFullMetadata: false, source: ImageSource.gallery);
  }

  Widget scanIcons(IconData iconData, void Function() onTab){
    return GestureDetector(
      onTap: onTab,
      child: Container(
        padding: const EdgeInsets.all(2),
        decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(22))
        ),
        child: Icon(iconData, size: 22,),
      ),
    );
  }

  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller?.pauseCamera();
    } else if (Platform.isIOS) {
      controller?.resumeCamera();
    }
  }

  /// 关闭闪光灯
  closeFlash() async {
    var flashStatus =  await controller?.getFlashStatus();
    if(flashStatus == true){
      controller?.toggleFlash();
    }
  }

  /// 二维码扫描结果监听
  void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((Barcode? scanData) {
      if(scanData !=null && scanData.code!=null){
        log.i("scan result ${scanData.code}");
        qrResultAction(scanData.code!, error: (result)=>scanErrorHandler(result));
      }
    });
  }

  /// 扫描结果处理
  qrResultAction(String msg, {void Function(String msg)? error}) async {
    closeFlash();
    IQrResult.parse(msg).action();
  }

  @override
  void dispose() {
    super.dispose();
    controller?.dispose();
  }

  /// 扫描异常结果处理
  void scanErrorHandler(String result){
      if(result.toLowerCase().startsWith("http")){
        context.pop();
        context.push("/web", extra: result);
      }else{
        bottomSheet(context, Text(result, style: TextStyle(color: textColor.color),));
      }
  }


}